package com.yw.atp.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.yw.atp.model.Staff;
import com.yw.atp.model.Weather;


@Repository
@Transactional
public class WeatherService{
	@PersistenceContext
    private EntityManager em;
	public List<Weather> getWeathers(Date date) throws ParseException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Query query = em.createQuery("select w FROM  Weather w where (w.date between :mDate1 and :mDate2) and w.status !='1' order by w.id desc");
		query.setParameter("mDate1",sdf2.parse(sdf.format(date)+" 00:00:00"));
		query.setParameter("mDate2",sdf2.parse(sdf.format(date)+" 23:59:59"));
		return (List<Weather>)query.getResultList();
	}
	
	public List<Weather> getPollingWeather(Integer maxID,String ids,Staff staff){
		try {
			StringBuffer sb = new StringBuffer();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			System.out.println(sdf2.format(sdf2.parse(sdf.format(new Date())+" 00:00:00")));
			System.out.println(sdf2.format(sdf2.parse(sdf.format(new Date())+" 23:59:59")));
			sb.append("select w FROM Weather w where (w.date between :mDate1 and :mDate2) and w.status !='1' and w.version > :maxID order by w.id desc");		
			Query query = em.createQuery(sb.toString());
			query.setParameter("mDate1",sdf2.parse(sdf.format(new Date())+" 00:00:00"));
			query.setParameter("mDate2",sdf2.parse(sdf.format(new Date())+" 23:59:59"));
			query.setParameter("maxID",maxID);
			return (List<Weather>)query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
